package com.xzy.web.controller;

import com.xzy.custom.TimeUtils;
import com.xzy.entities.*;
import com.xzy.service.*;
import com.xzy.web.form.BorrowRecordForm;
import com.xzy.web.form.SysUserForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author XiangZhongyi
 * ClassName: WeiXinController
 * date: 2022/3/31 14:01
 */
@RestController
@RequestMapping("/wx")
public class WeiXinController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private BookInformationService bookInformationService;
    @Autowired
    private BorrowRecordService borrowRecordService;
    @Autowired
    private BookRepertoryService bookRepertoryService;

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * */
    @RequestMapping("/login.action")
    public Object login(String username, String password){
        SysUser user = sysUserService.findByUserName(username);
        Map map = new HashMap();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        try {
            if (user == null){
                map.put("success",false);
                map.put("msg","该用户不存在");
            }else{
                if (!encoder.matches(password,user.getPassword())){
                    map.put("success",false);
                    map.put("msg","密码错误");
                }else {
                    map.put("success",true);
                    map.put("user",user);
                    map.put("msg","登录成功");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", "登录失败！");
        }
        return map;
    }

    /**
    * 注册
     * @param form 用户基本信息
    * */
    @RequestMapping("/register.action")
    public Object register(SysUserForm form){
        SysUser user = sysUserService.findByUserName(form.getUsername());
        SysRole role = sysRoleService.findByRole();
        Map<Object, Object> map = new HashMap<>();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        try {
            if (user != null) {
                map.put("success",false);
                map.put("msg","该用户已存在！");
            }else {
                form.setPassword(encoder.encode("123456"));
                sysUserService.insertUserRole(form,role.getId());
                map.put("success",true);
                map.put("msg","注册成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", "注册失败！");
        }
        return map;
    }
    /**
     *查找个人资料
     * @param id 用户id
     * */
    @RequestMapping("/userList.action")
    public Object userList(int id){
        Map map = new HashMap();
        try {
            SysUser userlist = sysUserService.findById(id);
            map.put("success",true);
            map.put("userlist",userlist);
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 修改个人资料
     * @param form 新的个人资料
     * */
    @RequestMapping("/userInformation.action")
    public Object userInformation(SysUserForm form){
        Map map = new HashMap();
        try {
            sysUserService.updateById(form);
            map.put("success",true);
            map.put("msg","修改资料成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 修改密码
     * @param oldpwd 原密码
     * @param newpwd 新密码
     * @param id 用户id
     * */
    @RequestMapping("/updatePwd.action")
    public Object updatePwd(String oldpwd, String newpwd, Integer id){
        Map map = new HashMap();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        try {
            SysUser user = sysUserService.findById(id);
            if (!encoder.matches(oldpwd,user.getPassword())){
                map.put("success",false);
                map.put("msg","原密码输入错误");
            }else {
                sysUserService.updatePwdById(encoder.encode(newpwd),id);
                map.put("success",true);
                map.put("msg","修改资料成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 获取图书列表
     * @param bookName 图书名
     * */
    @RequestMapping("/tushuList.action")
    public Object tushuList(String bookName){
        Map map = new HashMap();
        try {
            if (bookName.equals("")){
                List<BookInformation> bookList = bookInformationService.findBookInformationList();
                map.put("success",true);
                map.put("booklist",bookList);
            }else {
                List<BookInformation> bookList = bookInformationService.findByBookName(bookName);
                map.put("success",true);
                map.put("booklist",bookList);
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 获取图书信息
     * @param id 图书id
     * */
    @RequestMapping("/tushuInformation.action")
    public Object tushuInformation(Integer id){
        Map map = new HashMap();
        try {
            BookInformation bookInformation = bookInformationService.xwfindById(id);
            map.put("success",true);
            map.put("bookInformation",bookInformation);
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 借书
     * @param bookId 图书id
     * @param userId 用户id
     * */
    @RequestMapping("/borrow.action")
    public Object borrow(Integer bookId,Integer userId){
        Map map = new HashMap();
        BorrowRecordForm form = new BorrowRecordForm();
        String nowtime = TimeUtils.getStringTime();
        form.setApplyTime(nowtime);
        form.setUsername(userId);
        form.setBookName(bookId);
        form.setStatus("已借出");
        try {
            if(userId == null){
                map.put("success",false);
                map.put("msg","请先登录");
            }else{
                BookRepertory bookRepertory = bookRepertoryService.findByBookId(bookId);
                if (bookRepertory.getQuantity() == 0 || bookRepertory.getQuantity() == null){
                    map.put("success",false);
                    map.put("msg","库存不足");
                }else {
                    borrowRecordService.insertBorrowRecord(form);
                    bookRepertory.setQuantity(bookRepertory.getQuantity()-1);
                    bookRepertoryService.updateByBookId(bookRepertory,bookId);
                    map.put("success",true);
                    map.put("msg","借书成功");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 获取借书记录列表
     * @param bookName 图书名
     * */
    @RequestMapping("/huanshuList.action")
    public Object huanshuList(String bookName,Integer userId){
        Map map = new HashMap();
        List<Integer> bookId = borrowRecordService.findByUserId(userId);
        List<BookInformation> bookList = null;
        try {
            if (bookId.size() != 0){
                if (!bookName.equals("")){
                    bookList = bookInformationService.findByBookIdAndBookName(bookId,bookName,userId);
                    map.put("booklist",bookList);
                }else {
                    bookList = bookInformationService.findByBookId(bookId,userId);
                    map.put("booklist",bookList);
                }
                map.put("success",true);
            }else {
                map.put("success",true);
                map.put("booklist",bookList);
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 获取图书信息
     * @param borrowId 借书记录id
     * */
    @RequestMapping("/huanshuInformation.action")
    public Object huanshuInformation(Integer borrowId){
        Map map = new HashMap();
        try {
            BookInformation bookInformation = bookInformationService.xwfindBorrowById(borrowId);
            map.put("success",true);
            map.put("bookInformation",bookInformation);
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 新增评价
     * @param form 借书信息
     * */
    @RequestMapping("/operation.action")
    public Object operation(BorrowRecordForm form){
        Map map = new HashMap();
        try {
            borrowRecordService.insertOperation(form);
            map.put("success",true);
            map.put("msg","评价成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","获取失败");
        }
        return map;
    }

    /**
     * 还书
     * @param bookId 图书id
     * @param borrowId 借书记录id
     * */
    @RequestMapping("/returnBook.action")
    public Object returnBook(Integer bookId,Integer borrowId){
        Map map = new HashMap();
        BookRepertory bookRepertory = bookRepertoryService.findByBookId(bookId);
        Integer quantity = bookRepertory.getQuantity() + 1;
        try {
            borrowRecordService.updateStatus(borrowId);
            bookRepertoryService.updateQuantity(quantity,bookId);
            map.put("success",true);
            map.put("msg","还书成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","还书失败");
        }
        return map;
    }

    /**
     * 下载
     * @param uuid
     * @param request
     * @param response
     */
    @RequestMapping(value = "/download")
    @ResponseBody
    private void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
        bookInformationService.download(uuid, request, response);
    }
}
